package com.example.service.impl;

import com.example.constant.MessageConstant;
import com.example.context.BaseContext;
import com.example.dto.OrdersEmployeeDTO;
import com.example.dto.OrdersPageQueryDTO;
import com.example.dto.OrdersRejectionDTO;
import com.example.entity.*;
import com.example.mapper.InventoryDao;
import com.example.mapper.OrderDetailDao;
import com.example.mapper.OrdersEmployeeDao;
import com.example.mapper.StoreShoppingCartDao;
import com.example.result.PageResult;
import com.example.result.Result;
import com.example.service.OrdersEmployeeService;
import com.example.vo.OrderEmployeeVO;
import com.example.vo.OrderSubmitVO;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * (OrdersEmployee)表服务实现类
 *
 * @author makejava
 * @since 2024-04-16 16:13:36
 */
@Service("ordersEmployeeService")
public class OrdersEmployeeServiceImpl implements OrdersEmployeeService {
    @Resource
    private OrdersEmployeeDao ordersEmployeeDao;

    @Autowired
    private StoreShoppingCartDao storeShoppingCartDao;

    @Autowired
    private OrderDetailDao orderDetailDao;

    @Autowired
    private InventoryDao inventoryDao;
    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public OrdersEmployee queryById(Long id) {
        return this.ordersEmployeeDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param ordersEmployee 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<OrdersEmployee> queryByPage(OrdersEmployee ordersEmployee, PageRequest pageRequest) {
        long total = this.ordersEmployeeDao.count(ordersEmployee);
        return new PageImpl<>(this.ordersEmployeeDao.queryAllByLimit(ordersEmployee, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param ordersEmployee 实例对象
     * @return 实例对象
     */
    @Override
    public OrdersEmployee insert(OrdersEmployee ordersEmployee) {
        this.ordersEmployeeDao.insert(ordersEmployee);
        return ordersEmployee;
    }

    /**
     * 修改数据
     *
     * @param ordersEmployee 实例对象
     * @return 实例对象
     */
    @Override
    public OrdersEmployee update(OrdersEmployee ordersEmployee) {
        this.ordersEmployeeDao.update(ordersEmployee);
        return this.queryById(ordersEmployee.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.ordersEmployeeDao.deleteById(id) > 0;
    }

    //下单
    @Override
    @Transactional
    public Result submit(OrdersEmployeeDTO ordersEmployeeDTO) {
        //查询当前用户购物车数据
        Long userId = BaseContext.getCurrentId();
        Long storeId = BaseContext.getCurrentId2();
        StoreShoppingCart shoppingCart = StoreShoppingCart.builder()
                .userId(userId)
                .storeId(storeId)
                .build();
        List<StoreShoppingCart> shoppingCartList = storeShoppingCartDao.list(shoppingCart);
        if(shoppingCartList==null || shoppingCartList.size()==0){
            return Result.error(null, MessageConstant.SHOPPING_CART_IS_NULL);
//            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表插入1条数据
        OrdersEmployee orders = new OrdersEmployee();
        BeanUtils.copyProperties(ordersEmployeeDTO,orders);
        //订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setOrderTime(LocalDateTime.now());
        ordersEmployeeDao.insert(orders);

        //向订单明细表插入n条数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        for(StoreShoppingCart shoppingCart1:shoppingCartList){
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart1,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }

        orderDetailDao.insertBatch(orderDetails);

        //修改库存信息
        inventoryDao.updateBatch(shoppingCartList);

        //清空当前购物车数据
        storeShoppingCartDao.deleteByUserIdAndStoreId(userId,storeId);


        //封装vo返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();

        return Result.success(orderSubmitVO);
    }

    @Override
    public Result page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        com.github.pagehelper.Page<OrdersEmployee> page = ordersEmployeeDao.pageQuery(ordersPageQueryDTO);
        return Result.success(new PageResult(page.getTotal(),page.getResult()));
    }

    @Override
    public Result rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据id查询订单
        OrdersEmployee ordersDB = ordersEmployeeDao.queryById(ordersRejectionDTO.getId());
        OrdersEmployee orders = new OrdersEmployee();
        BeanUtils.copyProperties(ordersDB,orders);

        orders.setStatus(7);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        ordersEmployeeDao.update(orders);

        return Result.success(orders);
    }

    @Override
    public Result detailById(Long id) {
        OrdersEmployee ordersEmployee = ordersEmployeeDao.queryById(id);
        if(ordersEmployee == null){
            return Result.error("订单id错误");
        }
        OrderEmployeeVO orderEmployeeVO = new OrderEmployeeVO();
        BeanUtils.copyProperties(ordersEmployee,orderEmployeeVO);

        List<OrderDetail> orderDetails = orderDetailDao.getByOrderId(orderEmployeeVO.getId());
        orderEmployeeVO.setOrderDetailList(orderDetails);

        return Result.success(orderEmployeeVO);
    }
}
